<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function Node(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(null)
        var c = new Node(2)
        var d = new Node(3)
        var e = new Node(4)
        var f = new Node(5)
        var g = new Node(6)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g

        var aa = new Node(1)
        var bb = new Node(2)
        aa.left = bb


        /* 
            时间：O(n)
            空间：O(n)
        */
        var hasPathSum = (root, targetSum) => {
            if (!root) {
                return false
            }
            return traverse(root, targetSum - root.val)
        } 

        function traverse (cur, count) {
            // 注意判断叶子节点的办法
            if (!cur.left && !cur.right && count === 0) return true // 叶子节点找到路径
            if (!cur.left && !cur.right) return false // 叶子结点没有找到路径

            if(cur.left) {
                count -= cur.left.val
                // 为什么这里要做if判断并return，这里是递归，如果左子树递归后满足条件，则直接return true
                if (traverse(cur.left, count)) return true
                // 回溯
                count += cur.left.val
            }

            if (cur.right) {
                count -= cur.right.val
                // 右子树递归满足条件
                if (traverse(cur.right, count)) return true
                // 回溯
                count += cur.right.val
            }
            // 没有找到满足条件的值
            return false
        }
        console.log(hasPathSum(a, 8));
    </script>
</body>

</html>